package com.qiankan.qmsj;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;

import com.qiankan.qmsj.activity.BaseActivity;
import com.qiankan.qmsj.activity.LogInActivity;
import com.qiankan.qmsj.db.UserDBHelper;
import com.qiankan.qmsj.event.NetWorkChangeEvent;
import com.qiankan.qmsj.event.TypeEvent;
import com.qiankan.qmsj.fragment.ClassifyFragment;
import com.qiankan.qmsj.fragment.MainFragment;
import com.qiankan.qmsj.fragment.MyFragment;
import com.qiankan.qmsj.runtimepermissions.PermissionsManager;
import com.qiankan.qmsj.runtimepermissions.PermissionsResultAction;
import com.qiankan.qmsj.widget.TipToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindViews;

public class MainActivity extends BaseActivity {
    private long preActiveTime = 0;
    private int index;
    private int currentTabIndex;
    private HashMap<Integer, Fragment> mFragmentCache = new HashMap<>();
    @BindViews({R.id.btn_main, R.id.btn_category, R.id.btn_my})
    Button[] mTabs;

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        requestPermissions();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        mFragmentCache.put(currentTabIndex, createFragment(currentTabIndex));
        getFragmentManager().beginTransaction().add(R.id.fragment_container, mFragmentCache.get(currentTabIndex)).commit();
        mTabs[0].setSelected(true);
    }

    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {

            }

            @Override
            public void onDenied(String permission) {
                TipToast.toast(MainActivity.this, "拒绝权限可能影响app的正常使用！");
            }
        });
    }

    /**
     * on tab clicked
     *
     * @param view
     */
    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_main:
                index = 0;
                break;
            case R.id.btn_category:
                index = 1;
                EventBus.getDefault().post(new TypeEvent(""));
                break;
            case R.id.btn_my:
                if (!checkLogIn()) {
                    startActivity(LogInActivity.newIntent(this));
                    return;
                }
                index = 2;
                break;
        }
        changeFragment();
    }

    private boolean checkLogIn() {
        return UserDBHelper.getInstance(this).getUserInfo() != null;
    }

    private void changeFragment() {
        if (currentTabIndex != index) {
            FragmentTransaction trx = getFragmentManager().beginTransaction();
            trx.hide(mFragmentCache.get(currentTabIndex));
            if (mFragmentCache.get(index) == null) {
                mFragmentCache.put(index, createFragment(index));
                trx.add(R.id.fragment_container, mFragmentCache.get(index));
            } else if (!mFragmentCache.get(index).isAdded()) {
                trx.add(R.id.fragment_container, mFragmentCache.get(index));
            }
            trx.show(mFragmentCache.get(index)).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        // set current tab selected
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    private Fragment createFragment(int index) {
        switch (index) {
            case 0:
                return new MainFragment();
            case 1:
                return new ClassifyFragment();
            case 2:
                return new MyFragment();
        }
        return null;
    }

    public void setCurrentTab(int index) {
        this.index = index;
        changeFragment();
        mTabs[index].setSelected(true);
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - preActiveTime > 3000) {
            preActiveTime = System.currentTimeMillis();
            TipToast.toast(this, "再按一次退出应用!");
            return;
        }
        super.onBackPressed();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NetWorkChangeEvent event) {
        showNoNetworkDialog(event.isHasNetWork());
    }

    private void showNoNetworkDialog(boolean hasNetwork) {
        if (!hasNetwork) {
            //提示对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("网络设置提示").setMessage("网络连接不可用，是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = null;
                    //判断手机系统的版本  即API大于10 就是3.0或以上版本
                    if (android.os.Build.VERSION.SDK_INT > 10) {
                        intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                    } else {
                        intent = new Intent();
                        ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
                        intent.setComponent(component);
                        intent.setAction("android.intent.action.VIEW");
                    }
                    startActivity(intent);
                }
            }).setNegativeButton("取消", null).show();
        }
    }
}
